package com.linkage.jz.bankruptcy.fragment.Message;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Person.PersonSettingIntrActivity;
import com.linkage.jz.bankruptcy.adapter.NoticeRecyclerViewAdapter;
import com.linkage.jz.bankruptcy.adapter.RecyclerViewAdapter;
import com.linkage.jz.bankruptcy.bean.NormalModel;
import com.linkage.jz.bankruptcy.bean.NoticeInfo;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.utils.Utils;
import com.linkage.jz.bankruptcy.widget.Divider;
import com.linkage.jz.bankruptcy.widget.LoginNoticeDialog;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

import cn.bingoogolapple.androidcommon.adapter.BGAOnItemChildClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnItemChildLongClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnRVItemClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnRVItemLongClickListener;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/7/30.
 */

public class MsgNoticeFragment extends Fragment implements BGAOnRVItemClickListener, BGAOnRVItemLongClickListener, BGAOnItemChildClickListener, BGAOnItemChildLongClickListener {

    //显示信息
    private TextView text;
    //    private static final String TAG = RecyclerViewDemoActivity.class.getSimpleName();
    private NoticeRecyclerViewAdapter mAdapter;
    private ArrayList<NoticeInfo> mData;
    private LinearLayout ll_nodata;
    private RecyclerView mDataRv;
    private ShapeLoadingDialog shapeLoadingDialog ;

    ArrayList<Fragment> fragments = new ArrayList<Fragment>();

    Boolean initData = false;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_msg_notice, container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init(view);
        initRecyclerView(view);
        getData();
        initData = true;
        shapeLoadingDialog = new ShapeLoadingDialog(getActivity());

    }
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && initData) {
            //相当于Fragment的onResume
          getData();

        } else {
            //相当于Fragment的onPause
//            int j=0;
        }
    }


    private void init(View view) {
//        text = (TextView) view.findViewById(R.id.fragment_textview);
//        text.setText("GroupChildrenHasBuy");

    }

    private void initRecyclerView(View view) {
        ll_nodata = (LinearLayout) view.findViewById(R.id.ll_nodata);
        mDataRv = (RecyclerView) view.findViewById(R.id.rv_recyclerview_data);
        mDataRv.addItemDecoration(new Divider(getActivity()));

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mDataRv.setLayoutManager(layoutManager);

        mAdapter = new NoticeRecyclerViewAdapter(mDataRv);
        mAdapter.setOnRVItemClickListener(this);
        mAdapter.setOnRVItemLongClickListener(this);
        mAdapter.setOnItemChildClickListener(this);
        mAdapter.setOnItemChildLongClickListener(this);

        mDataRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (RecyclerView.SCROLL_STATE_DRAGGING == newState) {
                    mAdapter.closeOpenedSwipeItemLayoutWithAnim();
                }
            }
        });
        mData = new ArrayList<NoticeInfo>();
        NoticeInfo model = new NoticeInfo();
        model.setId("1");
        model.setTitle("title");
        model.setTitle("111");
//        mData.add(model);

//        mData
//        mData = DataEngine.loadNormalModelDatas();
        mAdapter.setData(mData);
        mDataRv.setAdapter(mAdapter);
    }

    @Override
    public void onItemChildClick(ViewGroup parent, View childView, int position) {
        NoticeInfo model = mAdapter.getItem(position);
        if (childView.getId() == R.id.tv_item_bgaswipe_delete) {
//            mAdapter.closeOpenedSwipeItemLayoutWithAnim();
//            mAdapter.removeItem(position);
            DelData(model.getId(),position);
        }
        if (childView.getId() == R.id.et_item_bgaswipe_read) {
//            mAdapter.closeOpenedSwipeItemLayoutWithAnim();
//            mAdapter.removeItem(position);
            UnReadFlag(model.getId());
        }
    }

    @Override
    public boolean onItemChildLongClick(ViewGroup parent, View childView, int position) {
        if (childView.getId() == R.id.tv_item_bgaswipe_delete) {
//            Toast.makeText(getActivity(), "长按了删除 " + mAdapter.getItem(position).getTitle(), Toast.LENGTH_SHORT).show();
            return true;
        }
        return false;
    }

    @Override
    public void onRVItemClick(ViewGroup parent, View itemView, int position) {
        NoticeInfo model = mAdapter.getItem(position);
        if(model !=null) {
//            PersonSettingIntrActivity.start(getActivity(),model.title,model.id);
        }
//        Toast.makeText(getActivity(), "点击了条目 " + mAdapter.getItem(position).getTitle(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean onRVItemLongClick(ViewGroup parent, View itemView, int position) {
//        Toast.makeText(getActivity(), "长按了条目 " + mAdapter.getItem(position).getTitle(), Toast.LENGTH_SHORT).show();
        return true;
    }


    public void getData()
    {

        if(BankruptcyApp.tokeninfo == null|| BankruptcyApp.tokeninfo.getToken() == null)
        {

            return;
        }

        ll_nodata.setVisibility(View.GONE);
//        shapeLoadingDialog.setLoadingText("加载中...");
//        shapeLoadingDialog.setCanceledOnTouchOutside(false);
//        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong()+"";
        String timestamp =System.currentTimeMillis()+"";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken","");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId","");
        if("".equalsIgnoreCase(userToken))
        {

            return;
        }
        RequestBody requestBody = new FormBody.Builder()
                .add("appid","1000000001")
                .add("nonce",rom)
                .add("timestamp", timestamp)
                .add("userToken", userToken)
                .add("token", BankruptcyApp.tokeninfo.getToken())
//                .add("token", "")
                .add("pageNumber","1")
                .add("pageSize","100")
                .add("msgType","1")


                .build();

        String url = Consts.WEBURL_MSGLIST;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {


                String str = response.body().string();
                try{
                    JSONObject object = new JSONObject(str);
                    mData.clear();
                    if  (object.optInt("code") == -10004 || (object.optInt("code") == -10003))
                    {

                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                LoginNoticeDialog.showPage(object.optString("msg"));
                            }

                        });

                        return;
                    }
                    if  (object.optInt("code") == -10004 || (object.optInt("code") == -10003))
                    {

                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                LoginNoticeDialog.showPage(object.optString("msg"));
                            }

                        });

                        return;
                    }
                    if(object.optInt("code") == 0)
                    {
                        JSONObject jsondata = object.getJSONObject("data");
                        JSONArray ary = jsondata.getJSONArray("list");
                        for(int i=0;i<ary.length();i++)
                        {
                            JSONObject data = ary.getJSONObject(i);
                            NoticeInfo model = new NoticeInfo();
                            model.setId(data.getString("id"));
                            model.setTitle(data.getString("title"));

                            String time = data.getString("opAt");
                            time=  Utils.timeStamp2Date(Long.parseLong(time)*1000,"yyyy-MM-dd HH:mm:ss");
                            model.setOpAt(time);
                            mData.add(model);
                        }
                        if(mData.size()>0)
                        {

                            getActivity().runOnUiThread(new Runnable() {

                                @Override
                                public void run() {
                                    //更新UI
                                    ll_nodata.setVisibility(View.GONE);
                                    mDataRv.setVisibility(View.VISIBLE);
                                }

                            });
                        }else{
                            getActivity().runOnUiThread(new Runnable() {

                                @Override
                                public void run() {
                                    //更新UI
                                    ll_nodata.setVisibility(View.VISIBLE);
                                    mDataRv.setVisibility(View.GONE);
                                }

                            });
                        }
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                mAdapter.notifyDataSetChanged();

                            }

                        });


//                        mAdapter.notifyDataSetChanged();

                    }else {

                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                ll_nodata.setVisibility(View.VISIBLE);
                                mDataRv.setVisibility(View.GONE);
                            }

                        });

                    }
                    str = "";
                }catch (Exception ex)
                {
                    ex.printStackTrace();
                }
            }
        });
    }



    public void UnReadFlag(String msgId)
    {
        if(BankruptcyApp.tokeninfo == null|| BankruptcyApp.tokeninfo.getToken() == null)
        {
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
        Random random = new Random();
        String rom = random.nextLong()+"";
        String timestamp =System.currentTimeMillis()+"";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken","");

        if("".equalsIgnoreCase(userToken))
        {
            return;
        }
        RequestBody requestBody = new FormBody.Builder()
                .add("appid","1000000001")
                .add("nonce",rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken", userToken)
                .add("msgId",msgId)
                .build();

        String url = Consts.WEBURL_READONE;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                Log.d(TAG, "onFailure: " + e.getMessage());
                shapeLoadingDialog.dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();



                String str = response.body().string();
                try{
                    final JSONObject object = new JSONObject(str);
                    if  (object.optInt("code") == -10004 || (object.optInt("code") == -10003))
                    {

                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                LoginNoticeDialog.showPage(object.optString("msg"));
                            }

                        });

                        return;
                    }
                    if(object.optInt("code") == 0)
                    {
                        JSONObject dataobject = object.optJSONObject("data");


//                        Toast.makeText(PhoneLoginActivity.this,"请求成功，请查看短信"+object.optString("data"),Toast.LENGTH_SHORT).show();
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {

                                EventBus.getDefault().post(666);
                                //更新UI
                                Toast.makeText(getActivity(),"请求成功",Toast.LENGTH_SHORT).show();
                            }

                        });

                    }else{
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {

//                                Toast.makeText(getActivity(),"请求失败，请稍候再试",Toast.LENGTH_SHORT).show();
                            }

                        });
                    }


                }catch (Exception ex)
                {
                    ex.printStackTrace();
                }
            }
        });
    }

    public void DelData(String msgId,final int position)
    {
        if(BankruptcyApp.tokeninfo == null|| BankruptcyApp.tokeninfo.getToken() == null)
        {
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
        Random random = new Random();
        String rom = random.nextLong()+"";
        String timestamp =System.currentTimeMillis()+"";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken","");

        if("".equalsIgnoreCase(userToken))
        {
            return;
        }
        RequestBody requestBody = new FormBody.Builder()
                .add("appid","1000000001")
                .add("nonce",rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken", userToken)
                .add("msgId",msgId)
                .build();

        String url = Consts.WEBURL_DELMSG;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                Log.d(TAG, "onFailure: " + e.getMessage());
                shapeLoadingDialog.dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();



                String str = response.body().string();
                try{
                    final JSONObject object = new JSONObject(str);
                    if  (object.optInt("code") == -10004 || (object.optInt("code") == -10003))
                    {

                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                LoginNoticeDialog.showPage(object.optString("msg"));
                            }

                        });

                        return;
                    }
                    if(object.optInt("code") == 0)
                    {
//
//                        Toast.makeText(PhoneLoginActivity.this,"请求成功，请查看短信"+object.optString("data"),Toast.LENGTH_SHORT).show();
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {


                                //更新UI
                                mAdapter.closeOpenedSwipeItemLayoutWithAnim();
                                mAdapter.removeItem(position);
                                Toast.makeText(getActivity(),"请求成功",Toast.LENGTH_SHORT).show();
                            }

                        });

                    }else{
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {

//                                Toast.makeText(getActivity(),"请求失败，请稍候再试",Toast.LENGTH_SHORT).show();
                            }

                        });
                    }


                }catch (Exception ex)
                {
                    ex.printStackTrace();
                }
            }
        });
    }




}
